package com.manager.receipt.controller;

import com.manager.common.constant.MimicryTcpFileType;
import com.manager.common.constant.ResultVOEnum;
import com.manager.common.constant.TcpDataType;
import com.manager.common.constant.TcpFileReportDownloadType;
import com.manager.common.ssh.RemoteExecuteLinuxCommandTools;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.DateTools;
import com.manager.common.utils.LargeFileHttpUploadUtils;
import com.manager.common.utils.LargeFileUtils;
import com.manager.common.vo.ResultVO;
import com.manager.common.webscket.WebSocketServer;
import com.manager.model.DataHandle;
import com.manager.model.File_Entity;
import com.manager.model.FirstPageState;
import com.manager.model.SensitiveWordLog;
import com.manager.sensitive.service.SensitiveWordService;
import com.manager.system.service.FileService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.WebServer;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/receipt")
public class ReceiptController {

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    SensitiveWordService sensitiveWordService;

    @Autowired
    FileService fileService;
    private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @RequestMapping("/receive")
    public ResultVO receipt(@RequestBody String receiptJson) {
        try{
            System.err.println("receive>>>>>>>>>>" + receiptJson);
            webSocketServer.sendToClient(receiptJson);
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/exceptionContainers")
    public ResultVO exceptionContainers(@RequestBody String exceptionContainersJson) {
        try{
            System.err.println("receive>>>>>>>>>>" + exceptionContainersJson);
            DataTools.putExceptionContainers(exceptionContainersJson);
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/tcpFileReport")
    public ResultVO gatherFileInfo(@RequestBody String tcpDataReport) {
        try{
            JSONObject jsonObject = JSONObject.fromObject(tcpDataReport);
            TcpDataType tcpDataType = TcpDataType.getTcpDataType(jsonObject.getInt("code"));
            System.err.println("tcpDataReport>>>>> "+tcpDataType.getDesc()+" >>>>>" + tcpDataReport);
            JSONObject content = jsonObject.getJSONObject("content");

            int tcpFileReport = content.getInt("type");
            TcpFileReportDownloadType tcpFileReportDownloadType = TcpFileReportDownloadType.getTcpFileReportType(tcpFileReport);
            System.err.println("TcpFileReportDownloadType>>>" + tcpFileReportDownloadType.getDesc() + ">>>>" + content.toString());
            if(tcpFileReportDownloadType == null){
                System.err.println("tcpFileReportDownloadType is null");
                return ResultVO.failed();
            }
            switch (tcpFileReportDownloadType) {
                case FIRST_PAGE_COUNT:
                    handleGatherFileInfo(content);
                    break;
                case TRAFFIC_EXCEPTION_GATHER:
                    handleTracfficExeptionFileInfo(content,tcpFileReportDownloadType);
                    break;
                case OUTER_LOG:
                    handleOuterLogFileInfo(content,tcpFileReportDownloadType);
                    break;
                case HTTP:
                    handleDownloadFile(content,tcpFileReportDownloadType);
                case TCP:
                    handleDownloadFile(content,tcpFileReportDownloadType);
                case ZYNQ_HANDLE:
                    handleDownloadFile(content,tcpFileReportDownloadType);
                case DECISION:
                    handDecisionFile(content,tcpFileReportDownloadType);
                default:
                    break;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    private ResultVO handDecisionFile(JSONObject receiptJson,TcpFileReportDownloadType tcpFileReportDownloadType) throws Exception{
        ResultVO resultVO = downloadRemoteFile(receiptJson);
        if(resultVO.getCode() == ResultVOEnum.FAILED.getCode()){
            return ResultVO.failed();
        }
        File file = (File)resultVO.getData();
        File_Entity fileEntity = new File_Entity();
        //
        String path = receiptJson.getString("filepath");
        //【1：多数裁决normal_vote.log  ，2: 加权裁决 weigh_vote.log，3：快速对比  fast_vote.log】
        if(path.contains("normal")){
            fileEntity.setOtherType("1");
        }else if(path.contains("weigh")){
            fileEntity.setOtherType("2");
        }else if(path.contains("fast")){
            fileEntity.setOtherType("3");
        }
        fileEntity.setBusinessType(tcpFileReportDownloadType.getCode());
        fileEntity.setFileName(tcpFileReportDownloadType.getDesc() + "-" + DateTools.getCurrentDateString("yyyyMMddHHmmss"));
        fileEntity.setUuidFileName(file.getName());
        fileEntity.setFilePath(file.getCanonicalPath()
                .substring(LargeFileHttpUploadUtils.getBasePath().length(), file.getCanonicalPath().length())
                .replaceAll("\\\\", "/"));
        fileEntity.setFileSize(LargeFileUtils.reckonFileSize(file.length()));
        fileEntity.setFileSuffix(file.getName().substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()));
        fileEntity.setFileStatus(0);
        fileEntity.setFileLongSize(file.length());

        fileService.addFile(fileEntity);

        return ResultVO.success(resultVO);
    }

    private ResultVO handleDownloadFile(JSONObject receiptJson,TcpFileReportDownloadType tcpFileReportDownloadType) throws Exception{
        ResultVO resultVO = downloadRemoteFile(receiptJson);
        if(resultVO.getCode() == ResultVOEnum.FAILED.getCode()){
            return ResultVO.failed();
        }
        File file = (File)resultVO.getData();
        File_Entity fileEntity = new File_Entity();
        fileEntity.setBusinessType(tcpFileReportDownloadType.getCode());
        fileEntity.setFileName(tcpFileReportDownloadType.getDesc() + "-" + DateTools.getCurrentDateString("yyyyMMddHHmmss"));
        fileEntity.setUuidFileName(file.getName());
        fileEntity.setFilePath(file.getCanonicalPath()
                .substring(LargeFileHttpUploadUtils.getBasePath().length(), file.getCanonicalPath().length())
                .replaceAll("\\\\", "/"));
        fileEntity.setFileSize(LargeFileUtils.reckonFileSize(file.length()));
        fileEntity.setFileSuffix(file.getName().substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()));
        fileEntity.setFileStatus(0);
        fileEntity.setFileLongSize(file.length());

        fileService.addFile(fileEntity);

        return ResultVO.success(resultVO);
    }

    private ResultVO handleOuterLogFileInfo(JSONObject receiptJson,TcpFileReportDownloadType tcpFileReportDownloadType) throws Exception {
        ResultVO resultVO = downloadRemoteFile(receiptJson);
        if(resultVO.getCode() == ResultVOEnum.FAILED.getCode()){
            return ResultVO.failed();
        }
        File file = (File)resultVO.getData();
        File_Entity fileEntity = new File_Entity();

        fileEntity.setBusinessType(tcpFileReportDownloadType.getCode());
        fileEntity.setFileName(tcpFileReportDownloadType.getDesc() + "-" + DateTools.getCurrentDateString("yyyyMMddHHmmss"));
        fileEntity.setUuidFileName(file.getName());
        fileEntity.setFilePath(file.getCanonicalPath()
                .substring(LargeFileHttpUploadUtils.getBasePath().length(), file.getCanonicalPath().length())
                .replaceAll("\\\\", "/"));
        fileEntity.setFileSize(LargeFileUtils.reckonFileSize(file.length()));
        fileEntity.setFileSuffix(file.getName().substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()));
        fileEntity.setFileStatus(0);
        fileEntity.setFileLongSize(file.length());

        fileService.addFile(fileEntity);

        return ResultVO.success(resultVO);
    }

    private ResultVO handleTracfficExeptionFileInfo(JSONObject content,TcpFileReportDownloadType tcpFileReportDownloadType) throws Exception {
        ResultVO resultVO = downloadRemoteFile(content);
        if(resultVO.getCode() == ResultVOEnum.FAILED.getCode()){
            return ResultVO.failed();
        }
        File file = (File)resultVO.getData();
        File_Entity fileEntity = new File_Entity();

        fileEntity.setBusinessType(tcpFileReportDownloadType.getCode());
        fileEntity.setFileName(tcpFileReportDownloadType.getDesc() + "-" + DateTools.getCurrentDateString("yyyyMMddHHmmss"));
        fileEntity.setUuidFileName(file.getName());
        fileEntity.setFilePath(file.getCanonicalPath()
                .substring(LargeFileHttpUploadUtils.getBasePath().length(), file.getCanonicalPath().length())
                .replaceAll("\\\\", "/"));
        fileEntity.setFileSize(LargeFileUtils.reckonFileSize(file.length()));
        fileEntity.setFileSuffix(file.getName().substring(file.getName().lastIndexOf(".") + 1,
                file.getName().length()));
        fileEntity.setFileStatus(0);
        fileEntity.setFileLongSize(file.length());

        fileService.addFile(fileEntity);

        return ResultVO.success(resultVO);
    }

    private ResultVO handleGatherFileInfo(JSONObject receiptJson) throws Exception {

        ResultVO resultVO = downloadRemoteFile(receiptJson);
        if(resultVO.getCode() == ResultVOEnum.FAILED.getCode()){
            return ResultVO.failed();
        }
        File file =(File) resultVO.getData();
        String jsonData = FileUtils.readFileToString(file, "utf-8");
        if(StringUtils.isEmpty(jsonData)){
            return ResultVO.failed();
        }
        JSONObject json = JSONObject.fromObject(jsonData);
        JSONArray jsonArray =  json.getJSONArray("top_sensitive_words");
        long timestamp = json.getLong("timestamp");
        String time = sdf.format(new Date(timestamp));
        for(int i = 0;i < jsonArray.size() ; i++){
            JSONObject temp = jsonArray.getJSONObject(i);
            SensitiveWordLog sensitiveWordLog = new SensitiveWordLog();
            sensitiveWordLog.setWord(temp.getString("word"));
            sensitiveWordLog.setHtiCount(temp.getInt("count"));
            sensitiveWordLog.setHitTime(time);
            sensitiveWordService.addHitLog(sensitiveWordLog);
        }
        DataTools.putStateCacheData(json);
        return ResultVO.success();
    }

    private ResultVO downloadRemoteFile(JSONObject jsonObject) {
        String path = jsonObject.getString("filepath");
        String suffix = path.substring(path.lastIndexOf(".") + 1, path.length());
        List<String> out = new ArrayList<>();
        String localFilePath = LargeFileHttpUploadUtils.getUploadFileSavePath() + "/"
                + UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        boolean flag = RemoteExecuteLinuxCommandTools.downloadFileBySftp(path,localFilePath,out);
        if(!flag){
            return ResultVO.failed();
        }
        File file = new File(localFilePath);
        if(!file.exists()){
            return ResultVO.failed();
        }
        return ResultVO.success(file);
    }

}
